package message;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WSServer {

	private WSUtils wsUtils = new WSUtils();
	public final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	public void start() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					System.out.println("start");
					wsUtils.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void stop() {
		wsUtils.stop();
	}

	public static void main(String[] args) {
		WSServer wsServer = new WSServer();
		wsServer.start();
	}

	public void send(String json, String uid) {
		allChannels.writeAndFlush(new TextWebSocketFrame(json), getMatcher(uid));
	}

	public ChannelMatcher getMatcher(final String uid) {
		return new ChannelMatcher() {

			@Override
			public boolean matches(Channel channel) {
				return channel.id().asLongText().equals(uid);
			}
		};
	}
}
